import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Config from '@/settings'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404','/register'] // 不重定向白名单

let routes = []

router.beforeEach(async(to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + Config.title
  }
  // start progress bar
  NProgress.start()
  if (Config.sso) {
    //debugger
    if (localStorage.getItem('access_token') && localStorage.getItem('username')) {
      if( to.path === '/login' && to.query.returnUrl ){
        // get user info
        const params = { phone: localStorage.getItem('username') }
        store.dispatch('user/getUserInfo', params).then(res => { // 拉取user_info
          window.location = decodeURIComponent(to.fullPath).split("returnUrl=")[1]
            + '?access_token=' + localStorage.getItem('access_token')
            + '&refresh_token=' + localStorage.getItem('refresh_token')
            + '&token_type=' + localStorage.getItem('token_type')
            + '&expires_in=' + localStorage.getItem('expires_in')
            + '&username=' + localStorage.getItem('username')
            + '&userName=' + localStorage.getItem('userName')
            + '&id=' + localStorage.getItem('id')
            + '&role=' + localStorage.getItem('role')
        }).catch((error) => {
          //登录超时，刷新token或重新登陆
          const params = { refresh_token: localStorage.getItem('refresh_token') }
          store.dispatch('user/refreshToken', params).then(res => { // 拉取user_info
            resultData = res.data
            if (window.localStorage) {
              localStorage.setItem('access_token', resultData.access_token)
              localStorage.setItem('refresh_token', resultData.refresh_token)
              localStorage.setItem('token_type', resultData.token_type)
              localStorage.setItem('expires_in', resultData.expires_in)
              localStorage.setItem('username', resultData.username)
              localStorage.setItem('userName', resultData.userName)
              localStorage.setItem('id', resultData.userId)
              localStorage.setItem('role', resultData.type)
            } else {
              alert('此浏览器不支持保存用户登录信息，请更换Chrome浏览器')
            }
            store.dispatch('user/getUserInfo', params).then(res => { // 拉取user_info  
              window.location = decodeURIComponent(to.fullPath).split("returnUrl=")[1]
                + '?access_token=' + localStorage.getItem('access_token')
                + '&refresh_token=' + localStorage.getItem('refresh_token')
                + '&token_type=' + localStorage.getItem('token_type')
                + '&expires_in=' + localStorage.getItem('expires_in')
                + '&username=' + localStorage.getItem('username')
                + '&userName=' + localStorage.getItem('userName')
                + '&id=' + localStorage.getItem('id')
                + '&role=' + localStorage.getItem('role')

            }).catch((error) => {
              //Message.error((error.response && error.response.data.message) || '获取用户信息失败，请联系管理员！')
              store.dispatch('user/resetToken')
              next()
              NProgress.done()
            })
          }).catch((error) => {
            //Message.error((error.response && error.response.data.message) || '获取用户信息失败，请联系管理员！')
            store.dispatch('user/resetToken')
            next()
            NProgress.done()
          })
        })
      } else if (to.path === '/login' || to.path === '/register') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done()
      } else {
        // 获取当前登录信息
        const hasGetUserInfo = store.getters.user.username
        if (hasGetUserInfo) {
          next()
        } else {
          
          // get user info
          const params = { phone: localStorage.getItem('username') }
          store.dispatch('user/getUserInfo', params).then(res => { // 拉取user_info
            // 获取用户对应的路由
            if (routes.length === 0) {
              // 是否初始化过路由列表，如果初始化就不会再一次初始化一次
              const generateRoutes = new Promise(function(resolve, reject) {
                // 获得用户菜单权限
                const params = { userId: store.getters.user.user_id, appId: Config.appId }
                store.dispatch('user/getCurrentRoutes', params).then(res => { // 拉取user_info
                  resolve(res)
                }).catch((error) => {
                  // remove token and go to login page to re-login
                  store.dispatch('user/resetToken')
                  Message.error(error.response.data.message || '获取菜单权限失败！')
                  next(`/login`)
                  NProgress.done()
                })
              })
              generateRoutes.then(function(data) {
                const currentRoutes = data && data.routerNames ? data.routerNames : []
                const authWords = data && data.authWords ? data.authWords : []
                store.dispatch('GenerateAuthWords', authWords)
                store.dispatch('GenerateRoutes', currentRoutes).then(() => { // 根据允许路由列表生成路由列表
                  store.getters.addRouters.push({ path: '*', redirect: '/404', hidden: true, children: [] })
                  router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                  routes = currentRoutes
                  next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                })
              })
            } else if (store.getters.addRouters.length < 0 && routes.length > 0) {
              store.dispatch('GenerateRoutes', routes).then(() => { // 根据允许路由列表生成路由列表
                store.getters.addRouters.push({ path: '*', redirect: '/404', hidden: true, children: [] })
                router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
              })
            } else if (store.getters.addRouters.length > 0) {
              next()
            }
          }).catch((error) => {
            //登录超时，刷新token或重新登陆
            const params = { refresh_token: localStorage.getItem('refresh_token') }
            store.dispatch('user/refreshToken', params).then(res => { // 拉取user_info
              resultData = res.data.data
              debugger
              if (window.localStorage) {
                localStorage.setItem('access_token', resultData.access_token)
                localStorage.setItem('refresh_token', resultData.refresh_token)
                localStorage.setItem('token_type', resultData.token_type)
                localStorage.setItem('expires_in', resultData.expires_in)
                localStorage.setItem('username', resultData.username)
                localStorage.setItem('userName', resultData.userName)
                localStorage.setItem('id', resultData.userId)
                localStorage.setItem('role', resultData.type)
              } else {
                alert('此浏览器不支持保存用户登录信息，请更换Chrome浏览器')
              }
              store.dispatch('user/getUserInfo', params).then(res => { // 拉取user_info
                // 获取用户对应的路由
                if (routes.length === 0) {
                  // 是否初始化过路由列表，如果初始化就不会再一次初始化一次
                  const generateRoutes = new Promise(function(resolve, reject) {
                    // 获得用户菜单权限
                    const params = { userId: store.getters.user.user_id, appId: Config.appId }
                    store.dispatch('user/getCurrentRoutes', params).then(res => { // 拉取user_info
                      resolve(res)
                    }).catch((error) => {
                      // remove token and go to login page to re-login
                      store.dispatch('user/resetToken')
                      Message.error(error.response.data.message || '获取菜单权限失败！')
                      next(`/login`)
                      NProgress.done()
                    })
                  })
                  generateRoutes.then(function(data) {
                    const currentRoutes = data && data.routerNames ? data.routerNames : []
                    const authWords = data && data.authWords ? data.authWords : []
                    store.dispatch('GenerateAuthWords', authWords)
                    store.dispatch('GenerateRoutes', currentRoutes).then(() => { // 根据允许路由列表生成路由列表
                      store.getters.addRouters.push({ path: '*', redirect: '/404', hidden: true, children: [] })
                      router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                      routes = currentRoutes
                      next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                    })
                  })
                } else if (store.getters.addRouters.length < 0 && routes.length > 0) {
                  store.dispatch('GenerateRoutes', routes).then(() => { // 根据允许路由列表生成路由列表
                    store.getters.addRouters.push({ path: '*', redirect: '/404', hidden: true, children: [] })
                    router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                    next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                  })
                } else if (store.getters.addRouters.length > 0) {
                  next()
                }
              }).catch((error) => {
                //Message.error((error.response && error.response.data.message) || '获取用户信息失败，请联系管理员！')
                store.dispatch('user/resetToken')
                next(`/login`)
                NProgress.done()
              })
            }).catch((error) => {
              //Message.error((error.response && error.response.data.message) || '获取用户信息失败，请联系管理员！')
              store.dispatch('user/resetToken')
              next(`/login`)
              NProgress.done()
            })
            
          })
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
        next()
      } else {
      // other pages that do not have permission to access are redirected to the login page.
        next('/login')
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
